/**
 * Created by 준영 on 14. 3. 27.
 */

var freeboardViewModel = (function(){

  function freeboardViewModel()
  {
      this.boardList = ko.observableArray();
      this.selectItem = ko.observable({});

      this.prevItem = ko.observable({});
      this.nextItem = ko.observable({});

      this.title = ko.observable();
  };

  Function.prototype.method = function(name, func)
  {
    this.prototype[name] = func;
  };


    freeboardViewModel.method("isDisabled", function(data)
    {

    });
    freeboardViewModel.method("onReflashCommand", function(data)
    {
        window.location.href = ("/freeboard?request=" + this.boardType);
    });
    freeboardViewModel.method("onDeleteCommand", function(data)
    {
        var _self = this;
        if(confirm("삭제 하시겠습니까?") == true)
        {
              callAjax('POST','api/deleteFreeboardItem', {"boardType" : _self.boardType, "_id" : _self.selectItem()._id}, function(result)
              {
                    if(result == "ok")
                    {
                        $('#readModal').modal('hide');
                        window.location.href = ("/freeboard?request=" + _self.boardType);
                    }
              });
        }

    });


    //List에서 등록 버튼 클릭시
    freeboardViewModel.method("onCreateCommand", function(data)
    {
        var _self = this;
        _self.editMode = "create";
        $('#writeModal').modal('show');
        $('#attachFileLayout').hide();

    });


    // 첨부파일 이미지 URL
    freeboardViewModel.method("getImages", function(data)
    {
        /*span.label.label-success(style='width: 1000px;') fff
        a.close.left x*/
       return getHost() + ":3003/upload/" + data.name;
    });

    // 첨부파일 이미지 이름 가져옴
    freeboardViewModel.method("getImageName", function(data)
    {
        var imageName =  data.name.split(data.token);
        return imageName[1];
    });

    freeboardViewModel.method("getFullName", function(data)
    {
        return data.name;
    });

    // 검색
    freeboardViewModel.method("onSearchCommand", function(data)
    {
       var searchText = $('#searchText').val();

       var _self = this;
        _self.boardList.removeAll();


        callAjax('GET', '/api/getTotalCount', { "boardType" : _self.boardType, 'searchText': searchText }, function(res)
        {

            _self.currentCount = 0;
            _self.totalCount = res.totalCount;
            if(_self.totalCount != 0)
            _self.getBoardList(0, 10, searchText, 0);

        });


    });

    freeboardViewModel.method("onMoreCommand", function(data)
    {
        var searchText = $('#searchText').val();
        if(this.currentCount == this.totalCount)
            return;
        this.getBoardList(this.boardList().length, 10, searchText, 0);


    });

    // 게시물 등록 또는 수정
    freeboardViewModel.method("onSaveCommand", function(data)
    {
        var _self = this;

        var subject = $('#subject').val();
        var body = $('#bodyContent').val();



        if(_self.editMode == "create") {


            var formData = new FormData($('#myForm')[0]);

            $.ajax({
                   type: 'POST',
                   url: '/api/fileUpload',
                   data: formData,
                   processData: false,
                   contentType: false,
                   success: function(data)
                   {
                       body = body.replace(/\n/g, '<br>');
                       if (data == "empty") {
                           callAjax('POST', '/api/writeFreeboard', {"boardType" : _self.boardType,'userID': user, 'subject': subject, 'body': body}, function (res) {
                               window.location.href = ("/freeboard");
                           });
                       }
                       else {
                           callAjax('POST', '/api/writeFreeboard', {"boardType" : _self.boardType,'userID': user, 'subject': subject, 'body': body, 'images': data}, function (res) {
                               window.location.href = ("/freeboard");

                           });
                       }
                   },
                   error: function(err) { alert('File Upload Error');}
                });
         //   $('#myForm').submit();j



        }
        else
        {
            var formData = new FormData($('#myForm')[0]);
            var checkboxArray = $('#imagesLayout :checkbox');
            var deleteImages = [];
            if(checkboxArray.length > 0) {

                for (var i=0; i <  checkboxArray.length; i++)
                {
                    if (checkboxArray[i].checked == true) {

                        deleteImages.push(($(checkboxArray[i]).attr('tag')));
                    }
                }
            }
            $.ajax({
                type: 'POST',
                url: '/api/fileUpload',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data)
                {
                    if (data == "empty") {
                        callAjax('POST', '/api/modifyFreeboardItem', {"boardType" : _self.boardType, "_id": _self.selectItem()._id, 'userID': user, 'subject': subject, 'body': body,  'deleteImages': deleteImages}, function (result) {
                            if (result == "ok") {
                                window.location.href = ("/freeboard");
                            } else {
                                alert("글 수정 실패");
                            }
                        });
                    }
                    else {


                        callAjax('POST', '/api/modifyFreeboardItem', {"boardType" : _self.boardType, "_id": _self.selectItem()._id, 'userID': user, 'subject': subject, 'body': body,'images':data, 'deleteImages': deleteImages}, function (result) {
                            if (result == "ok") {
                                window.location.href = ("/freeboard");
                            } else {
                                alert("글 수정 실패");
                            }
                        });
                    }
                },
                error: function(err) { alert('File Upload Error');}
            });


        }
    });

    freeboardViewModel.method("getThumbNailImage", function(data)
    {
        if(data.images != undefined && data.images.length > 0)
       return "http://localhost:3003/upload/" +  data.images[0].name;
        else
            return "http://localhost:3003/upload/default.png"
    });
    freeboardViewModel.method("onModifyCommand", function(data)
    {
        var _self = this;
        _self.editMode = "modify";
        $('#readModal').modal('hide');
        $('#writeModal').modal('show');
        $('#attachFileLayout').show();
        $('#subject').val(this.selectItem().subject);
        $('#bodyContent').val(this.selectItem().body);
    });

  freeboardViewModel.method("getCurrentSubject", function()
  {
      var _self = this;
      return _self.selectItem.Subject;
  });


  freeboardViewModel.method("onSelect", function(val)
  {

      var _self = this;

      callAjax('GET', '/api/getPrevAndNextItemIndex', {"boardType" : _self.boardType, "_id" : val._id}, function(result)
      {
          if(result.prevItem == null)
          {
              result.prevItem = {subject: "", _id:{}};
          }
          if(result.nextItem == null)
          {
              result.nextItem = {subject: "" , _id:{}};
          }
          _self.prevItem(result.prevItem);
          _self.nextItem(result.nextItem);

          result.currentItem.body = result.currentItem.body.replace("<br>", "\r\n");
          if(typeof result.currentItem.comments != "undefined") {
              result.currentItem.commentTotalCount = result.currentItem.comments.length;
          }
          else
          {
              result.currentItem.commentTotalCount = 0;
          }

          if(typeof result.currentItem.comments != 'undefined' ) {
              $.each(result.currentItem.comments, function (index, item) {
                  //     item.last_update = $.datepicker.formatDate('yy/mm/dd, hh:mm',new Date(item.last_update))

              });
          }

          if(user != result.currentItem.userID)
          {
              $('#btnDelete').attr('disabled', true);
              $('#btnEdit').attr('disabled', true);
          }
          else
          {
              $('#btnDelete').attr('disabled', false);
              $('#btnEdit').attr('disabled', false);
          }
          _self.selectItem(result.currentItem);

          $('#readModal').modal('show');
      });


    return "";
  });

   freeboardViewModel.method("isOwner", function()
   {
       if(typeof this.selectItem()._id  != 'undefined') {
           if (this.selectItem()._id != user) {
               return "display:none";
           }
       }
       return "";
   });
  freeboardViewModel.method("getMobile", function()
  {

    if(isMobile == true)
    {
      return "display:none";
    }
    return "";
  });

  freeboardViewModel.method("setWidth", function(tag)
  {

    if (isMobile) {
      if (tag == "nickname") {
        return "width: 20%";
      }
      else {
        return "width: 80%";
      }
    }
    else
    {
      if (tag == "nickname") {
        return "width: 10%";
      }
      else {
        return "width: 55%";
      }
    }
  });

  freeboardViewModel.method("getBoardList", function(index, limit, searchText, mode){
      var self = this;


      callAjax('GET', '/api/getFreeboardList', { "boardType" : self.boardType,"index" : index, "limit": limit,"searchText": searchText, "mode": mode}, function(result)
      {

          $.each(result, function(index, element)
          {
              var isoDate = new Date(element.last_update );
             var dateType = jQuery.format.getAgo(isoDate);
              var writeDate = {};
              switch(dateType)
              {
                  case "0":
                      writeDate =  $.format.date(isoDate, "HH:mm");
                      break;
                  case "1":
                      writeDate =  $.format.date(isoDate, "HH:mm");
                      break;
                  case "2":

                      writeDate =  $.format.date(isoDate, "MM-dd");
                      break;
                  default:
                      writeDate =  $.format.date(isoDate, "yy-MM-dd");
                      break;
              }


           /*   var writeDateTime = new Date( isoDate.getTime() + (isoDate.getTimezoneOffset() * 60000));*/
              self.boardList.push({"_id": element._id,"No": (self.totalCount - self.currentCount), "NickName": element.nickname, "UserID":  element.userID, "Subject" : element.subject,
                 "Body" : element.body,"Date" : writeDate.toString() , "Count" : element.readCount, "images": element.images});

              self.currentCount++;
          });
      });
  });


  return freeboardViewModel;
})();


function tog(v){return v?'addClass':'removeClass';}

$(document).on('input', '.clearable', function(){
    $(this)[tog(this.value)]('x');
}).on('mousemove', '.x', function( e ){
    $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');
}).on('click', '.onX', function(){
    $(this).removeClass('x onX').val('');
});

$(document).ready(function(){



   var _self = this;
  var viewModel = new freeboardViewModel();
      viewModel.boardType = getParameterByName("request");

    if(viewModel.boardType == "freeboard") {
        viewModel.Title = "자유 게시판";
    }
    else if(viewModel.boardType == "gallery")
    {
        viewModel.Title = "겔러리";
    }
    ko.applyBindings(viewModel);
    // TotalCount를 가져온다.
    callAjax('GET', '/api/getTotalCount', { "boardType": viewModel.boardType }, function(res)
    {

       viewModel.currentCount = 0;
        viewModel.totalCount = res.totalCount;
        viewModel.getBoardList(0,10, "", 0);

    });



    $('#searchText').on('keydown', function(e)
    {
        if(e.which == 13)
        {
           viewModel.onSearchCommand("");
        }
    });


    // 파일 첨부에서 파일 선택시
    $('#imgs').on("change", function(){
        //확장자 비교
        //http://stackoverflow.com/questions/14852090/jquery-check-for-file-extension-before-uploading

        var input = $(this);
        var files =  $('#imgs')[0].files;
        for (var i=0; i < files.length; i++)
        {
            var filename = files[i].name;
            var extension = filename.replace(/^.*\./, '');
            if (extension == filename) {
                extension = '';
            } else {
                extension = extension.toLowerCase();
            }

            if( (extension != 'jpg') && (extension != 'png') ) {
                //초기화
                //http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery
                var control = $("#imgs");
                control.replaceWith( control = control.clone( true ) );
                   $('#imgs')[0].form.reset();


                alert("이미지 파일은 JPG, PNG 확장자만 가능합니다.");

                return;
            }
        }

        var label = input.val().replace(/\\/g, '/').replace(/.*\//, '');

        input.trigger('fileselect', [files.length, label]);



        //이미지 파일은 JPG, PNG 확장자만 가능

    });

    $('.btn-file :file').on('fileselect', function(event, numFiles, label) {

        var input = $('#selectText');
            log = numFiles > 1 ? numFiles + ' files selected' : label;

        if( input.length ) {
            input.val(log);
        } else {
            if( log ) alert(log);
        }

    });


    //코멘트 등록
  $('#addComment').on('click', function(e)
  {
      var commentContent = $('#commentContent').val();
      callAjax('POST','/api/createComment', {"boardType" : viewModel.boardType, _id: viewModel.selectItem()._id, commentContent:commentContent }, function(res)
      {

      });
  });




});